/*
 *  Copyright 2010 asustatil.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package edu.upf.core;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 *
 * @author asustatil
 */
public class UserList {

    private List<User> userList;
    private Set<User> onlineUsers;
    private Set<User> offlineUsers;

    public UserList(){
        userList=new ArrayList();
        onlineUsers=new HashSet();
        offlineUsers=new HashSet();
    }

    public boolean addUser(User buddy){
        if(userList.contains(buddy)){
            return false;
        }
        offlineUsers.add(buddy);
        return userList.add(buddy);
    }

    public boolean updateUser(User buddy){
        
        if(buddy==null){
            return false;
        }

        if(buddy.isAvailable()){
            if(offlineUsers.remove(buddy)){
               return onlineUsers.add(buddy);
            }
            return false;
        }else{
            if(onlineUsers.remove(buddy)){
                return offlineUsers.add(buddy);
            }
            return false;
        }
    }

    public boolean removeUser(User buddy){
        if(userList.contains(buddy)){
            onlineUsers.remove(buddy);
            offlineUsers.remove(buddy);
            return userList.remove(buddy);
        }
        return false;
    }

    public User getUser(String address){
        Iterator i=userList.iterator();
        while(i.hasNext()){
            User currentUser=(User)i.next();
            if(currentUser.getAddress().equals(address)){
                return currentUser;
            }
        }
        return null;
    }

    public User getUser(int pos){
        return userList.get(pos);
    }
    
    public List<User> getUsers(){
        return userList;
    }

    public Set getOnlineUsers(){
        return onlineUsers;
    }

    public Set getOfflineUsers(){
        return offlineUsers;
    }

}
